package com.ruoyi.business.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.ruoyi.business.domain.CivilServants;
import com.ruoyi.business.domain.CivilServantsList;
import com.ruoyi.business.domain.temp.DegreeTemp;
import com.ruoyi.business.domain.vo.CivilServantsListVo;
import com.ruoyi.business.domain.vo.ResumeVo;
import com.ruoyi.business.mapper.CivilServantsListMapper;
import com.ruoyi.business.mapper.CivilServantsMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.business.constant.DegreeType.*;
import static com.ruoyi.business.utils.DES.decrypt;
import static com.ruoyi.business.utils.DES.encrypt;

@Service
public class CivilServantsService {

    @Autowired
    CivilServantsMapper civilServantsMapper;


    @Autowired
    CivilServantsListMapper civilServantsListMapper;

    @Value("${userId}")
    private Long ZJuserId;

    @Value("${userName}")
    private String userName;


    private static final String KEY = "12345678";

    public void delete(Long id) {
        Long userid = SecurityUtils.getUserId();
        Long userId = civilServantsMapper.getResume(id).getUserId();
        if (userId.equals(userid)) {
            int deleteResult = civilServantsMapper.delete(id);
            if (deleteResult == 0) {
                throw new RuntimeException("机关公务员删除失败");
            }
        } else {
            throw new RuntimeException("非本市级添加人员，禁止删除");
        }

    }

    public void add(CivilServants civilServants) {
        Long userid = SecurityUtils.getUserId();
        civilServants.setUserId(userid);
        int addResult = civilServantsMapper.save(civilServants);
        if (addResult == 0) {
            throw new RuntimeException("机关公务员新增失败");
        }
    }

    public void update(CivilServants civilServants) {
        Long userid = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        if (userid == ZJuserId || username.equals(userName)) {
            Long id = civilServants.getId();
            Long userId = civilServantsMapper.getResume(id).getUserId();
            if (userId.equals(userid)) {
                int updateResult = civilServantsMapper.update(civilServants);
                if (updateResult == 0) {
                    throw new RuntimeException("机关公务员修改失败");
                }
            } else {
                throw new RuntimeException("非本市级添加人员，禁止修改");
            }
        }
        int updateResult = civilServantsMapper.update(civilServants);
        if (updateResult == 0) {
            throw new RuntimeException("机关公务员修改失败");
        }
    }

    public void addExcel(MultipartFile file) throws IOException {
        InputStream inputStream = new BufferedInputStream(file.getInputStream());
        // 定义数据存储容器
        List<Map<Integer, String>> dataList = new ArrayList<>();
        // 构造监听器对象
        AnalysisEventListener<Map<Integer, String>> listener = new AnalysisEventListener<Map<Integer, String>>() {
            @Override
            public void invoke(Map<Integer, String> rowData, AnalysisContext context) {
                dataList.add(rowData); // 将每行数据添加到容器中
            }

            @Override
            public void extra(CellExtra extra, AnalysisContext context) {
                // 处理额外的单元格信息，比如合并单元格、批注等
                // ...
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {

            }
        };

        // 读取 Excel 文件
        EasyExcel.read(inputStream).registerReadListener(listener).sheet(0).doRead();

        List<CivilServants> civilServantsList = new ArrayList<>();
        // 遍历数据
        for (Map<Integer, String> rowData : dataList) {
            CivilServants civilServants = new CivilServants();
            Integer id = rowData.keySet().iterator().next();
            civilServants.setDepartment(rowData.get(id));
            civilServants.setName(rowData.get(id + 1));
            civilServants.setPosition(rowData.get(id + 2));
            if (rowData.get(id + 3).equals("男")) {
                civilServants.setSex(0);
            } else {
                civilServants.setSex(1);
            }
            civilServants.setEthnicGroup(rowData.get(id + 4));
            civilServants.setNativePlace(rowData.get(id + 5));
            civilServants.setBirthTime(rowData.get(id + 6));
            civilServants.setWorkTime(rowData.get(id + 7));
            civilServants.setPartyTime(rowData.get(id + 8));
            civilServants.setCommitteeTime(rowData.get(id + 9));
            civilServants.setNowPostTime(rowData.get(id + 10));
            civilServants.setNowLevelTime(rowData.get(id + 11));
            civilServants.setNowOfficeTime(rowData.get(id + 12));
            civilServants.setFullTimeDegree(rowData.get(id + 13));
            civilServants.setFullTimeGraduation(rowData.get(id + 14));
            civilServants.setOnJobDegree(rowData.get(id + 15));
            civilServants.setOnJobGraduation(rowData.get(id + 16));
            civilServantsList.add(civilServants);
        }
        Long userid = SecurityUtils.getUserId();
        for (CivilServants civilServants : civilServantsList) {
            civilServants.setUserId(userid);
            civilServantsMapper.save(civilServants);
        }
    }

    public List<CivilServants> list(Long userId, String name) {
        Long userid = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        if (userid == 1 || userid == ZJuserId || username.equals(userName)) {
//            if (userId != ZJuserId || name != null) {
            if ( userId !=null||name != null) {
                List<CivilServants> list = civilServantsMapper.list2(userId, name);
                return list;
            } else {
                List<CivilServants> list = civilServantsMapper.list();
                return list;
            }
        } else {
            if (name != null) {
                List<CivilServants> list = civilServantsMapper.list2(userid, name);
                return list;
            } else {
                List<CivilServants> listByUserId = civilServantsMapper.list(userid);
                return listByUserId;
            }
        }


    }

    public List<CivilServants> list() {
        Long userid = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        if (userid == 1 || userid == ZJuserId || username.equals(userName)) {
            List<CivilServants> list = civilServantsMapper.list();
            return list;
        } else {
            List<CivilServants> listByUserId = civilServantsMapper.list(userid);
            return listByUserId;
        }


    }


    /**
     * 用ruoyi自带的导入
     *
     * @param file
     * @throws IOException
     */
    public void insert(MultipartFile file, Long userId) throws IOException {
        ExcelUtil<CivilServants> util = new ExcelUtil<CivilServants>(CivilServants.class);
        List<CivilServants> civilServantsList = util.importExcel(file.getInputStream());
        for (CivilServants civilServants : civilServantsList) {
            civilServants.setUserId(userId);
            civilServantsMapper.save(civilServants);
        }
    }

    public ResumeVo getResume(Long id) {
        CivilServants civilServants = civilServantsMapper.getResume(id);
        List<CivilServantsList> list = civilServantsListMapper.getResume(id);
        List<ResumeVo.ListSummary> listSummaryList = list.stream()
                .map(obj -> {
                    try {
                        return new ResumeVo.ListSummary(obj.getProsCons(), decrypt(obj.getWorkList(), KEY));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());
        ResumeVo resumeVo = new ResumeVo();
        resumeVo.setCivilServants(civilServants);
        resumeVo.setListSummary(listSummaryList);
        return resumeVo;
    }

    public int sum(Long id) {
        if (id == null) {
            Long userId = SecurityUtils.getUserId();
            String username = SecurityUtils.getUsername();
            if (userId == 1 || userId == ZJuserId || username.equals(userName)) {
                int sum = civilServantsMapper.sum();
                return sum;
            } else {
                int sum = civilServantsMapper.sum(userId);
                return sum;
            }
        } else {
            int sum = civilServantsMapper.sum(id);
            return sum;
        }
    }


    public AjaxResult getDegree(Long id, String type) {
        int sum = 0;
        int undergraduate = 0;
        int graduate = 0;
        int doctor = 0;
        int other = 0;
        List<DegreeTemp> degreeTemp = new ArrayList<>();
        //全部干部
        if (type == null || type.equals("0")) {
//            if (id==null){
            Long userId = SecurityUtils.getUserId();
            String username = SecurityUtils.getUsername();
            if (userId == 1 || userId == ZJuserId || username.equals(userName)) {
                sum = civilServantsMapper.sum();
                degreeTemp = civilServantsMapper.list().stream()
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            } else {
                sum = civilServantsMapper.sum(userId);
                degreeTemp = civilServantsMapper.list(userId).stream()
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            }
//            }else {
//                sum=civilServantsMapper.sum(id);
//                degreeTemp = civilServantsMapper.list(id).stream()
//                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
//                        .collect(Collectors.toList());
//            }
        }
//处级干部
        else if (type.equals("1")) {
//            if (id==null){
            Long userId = SecurityUtils.getUserId();
            String username = SecurityUtils.getUsername();
            if (userId == 1 || userId == ZJuserId || username.equals(userName)) {
                sum = (int) civilServantsMapper.list().stream()
                        .filter(s -> s.getNowOfficeTime() != null && !s.getNowOfficeTime().equals(""))
                        .count();
                degreeTemp = civilServantsMapper.list().stream()
                        .filter(s -> s.getNowOfficeTime() != null && !s.getNowOfficeTime().equals(""))
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            } else {
                sum = (int) civilServantsMapper.list(userId).stream()
                        .filter(s -> s.getNowOfficeTime() != null && !s.getNowOfficeTime().equals(""))
                        .count();
                degreeTemp = civilServantsMapper.list(userId).stream()
                        .filter(s -> s.getNowOfficeTime() != null && !s.getNowOfficeTime().equals(""))
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            }
//            }else {
//                sum = (int) civilServantsMapper.list(id).stream()
//                        .filter(s -> s.getNowOfficeTime() != null && !s.getNowOfficeTime().equals(""))
//                        .count();
//                degreeTemp = civilServantsMapper.list(id).stream()
//                        .filter(s -> s.getNowOfficeTime() != null && !s.getNowOfficeTime().equals(""))
//                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
//                        .collect(Collectors.toList());
//            }
        }
//科级干部
        else if (type.equals("2")) {
//            if (id==null){
            Long userId = SecurityUtils.getUserId();
            String username = SecurityUtils.getUsername();
            if (userId == 1 || userId == ZJuserId || username.equals(userName)) {
                sum = (int) civilServantsMapper.list().stream()
                        .filter(s -> s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals("") && s.getDirectorTime() != null)
                        .count();
                degreeTemp = civilServantsMapper.list().stream()
                        .filter(s -> s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals("") && s.getDirectorTime() != null)
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            } else {
                sum = (int) civilServantsMapper.list(userId).stream()
                        .filter(s -> s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals("") && s.getDirectorTime() != null)
                        .count();
                degreeTemp = civilServantsMapper.list(userId).stream()
                        .filter(s -> s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals("") && s.getDirectorTime() != null)
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            }
//            }else {
//                sum = (int) civilServantsMapper.list(id).stream()
//                        .filter(s -> s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
//                        .filter(s -> s.getNowOfficeTime() == null ||s.getNowOfficeTime().equals("")&& s.getDirectorTime() != null)
//                        .count();
//                degreeTemp = civilServantsMapper.list(id).stream()
//                        .filter(s -> s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
//                        .filter(s -> s.getNowOfficeTime() == null ||s.getNowOfficeTime().equals("")&& s.getDirectorTime() != null)
//                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
//                        .collect(Collectors.toList());
//            }
        }
        //其他职级
        else if (type.equals("3")) {
//            if (id==null){
            Long userId = SecurityUtils.getUserId();
            String username = SecurityUtils.getUsername();
            if (userId == 1 || userId == ZJuserId || username.equals(userName)) {
                sum = (int) civilServantsMapper.list().stream()
                        .filter(s -> s.getDirectorTime() == null || s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals(""))
                        .count();
                degreeTemp = civilServantsMapper.list().stream()
                        .filter(s -> s.getDirectorTime() == null || s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals(""))
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            } else {
                sum = (int) civilServantsMapper.list(userId).stream()
                        .filter(s -> s.getDirectorTime() == null || s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals(""))
                        .count();
                degreeTemp = civilServantsMapper.list(userId).stream()
                        .filter(s -> s.getDirectorTime() == null || s.getDirectorTime().equals(""))
                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals(""))
                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
                        .collect(Collectors.toList());
            }
//            }else {
//                sum = (int) civilServantsMapper.list(id).stream()
//                        .filter(s -> s.getDirectorTime() == null || s.getDirectorTime().equals("") )
//                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals(""))
//                        .count();
//                degreeTemp = civilServantsMapper.list(id).stream()
//                        .filter(s -> s.getDirectorTime() == null || s.getDirectorTime().equals("") )
//                        .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals(""))
//                        .map(obj -> new DegreeTemp(obj.getId(), obj.getFullTimeDegree(), obj.getOnJobDegree()))
//                        .collect(Collectors.toList());
//            }
        }

        return getAjaxResult(degreeTemp, undergraduate, graduate, sum, doctor);
    }

    /**
     * 学历统计封装方法
     *
     * @param degreeTemp
     * @param undergraduate
     * @param graduate
     * @param sum
     * @param doctor
     * @return
     */
    private static AjaxResult getAjaxResult(List<DegreeTemp> degreeTemp, int undergraduate, int graduate, int sum, int doctor) {
        int other;
        for (DegreeTemp temp : degreeTemp) {
            if (temp.getOnJobDegree() != null) {
                switch (temp.onJobDegree) {
                    case UNDERGRADUATE:
                        undergraduate++;
                        break;
                    case GRADUATE:
                        graduate++;
                        break;
                    case MASTER:
                        graduate++;
                        break;
                }
            } else if (temp.getFullTimeDegree() != null) {
                switch (temp.fullTimeDegree) {
                    case UNDERGRADUATE:
                        undergraduate++;
                        break;
                    case GRADUATE:
                        graduate++;
                        break;
                    case MASTER:
                        graduate++;
                        break;
                }
            }

        }
        AjaxResult ajax = new AjaxResult();
        ajax.put("undergraduate_quantity", undergraduate);
        ajax.put("graduate_quantity", graduate);
        other = sum - undergraduate - graduate;
        ajax.put("other_quantity", other);
        return ajax;
    }


    public AjaxResult getOffice(Long id) {
        int sum = 0;
        List<CivilServants> list = new ArrayList<>();

//        if (id==null){
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        if (userId == 1 || userId == ZJuserId || username.equals(userName)) {
            sum = civilServantsMapper.sum();
            list = civilServantsMapper.list();
        } else {
            sum = civilServantsMapper.sum(userId);
            list = civilServantsMapper.list(userId);
        }
//        }else{
//            sum = civilServantsMapper.sum(id);
//            list = civilServantsMapper.list(id);
//        }
        long officeCount = list.stream()
//                .filter(s->s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
                .filter(s -> s.getNowOfficeTime() != null && !s.getNowOfficeTime().equals(""))
                .count();
        List<CivilServants> directorList = list.stream()
                .filter(s -> s.getDirectorTime() != null && !s.getDirectorTime().equals(""))
                .collect(Collectors.toList());
        long directorCount = directorList.stream()
                .filter(s -> s.getNowOfficeTime() == null || s.getNowOfficeTime().equals("") && s.getDirectorTime() != null)
                .count();
        AjaxResult ajax = new AjaxResult();
        ajax.put("officeCount", officeCount);
        ajax.put("directorCount", directorCount);
        ajax.put("other", sum - officeCount - directorCount);
        return ajax;
    }

}
